package com.excilys.gwtfirst.domain.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.excilys.gwtfirst.domain.dao.impl.UserDAO;
import com.excilys.gwtfirst.domain.model.User;
import com.excilys.gwtfirst.domain.service.api.AuthenticationService;
import com.excilys.gwtfirst.domain.service.api.security.CustomUserDetails;
import com.excilys.gwtfirst.domain.service.api.security.UserRole;

@Service(value = "myAuthenticationService")
public class AuthenticationServiceImpl implements AuthenticationService {

	@Autowired
	private UserDAO userDAO;

	@Override
	public CustomUserDetails loadUserByUsername(String login) //
			throws UsernameNotFoundException {

		// Get the user
		User user = userDAO.findByLogin(login);

		// If null throw an exception
		if (user == null)
			throw new UsernameNotFoundException(login + " : cet utilisateur n'existe pas.");

		// Create and return a spring security user
		return createUserDetails(user);
	}

	/** Create a spring security UserDetail from a User */
	private CustomUserDetails createUserDetails(User user) {

		// Initialize values
		String username = user.getLogin();
		String password = user.getPassword();
		boolean enabled = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		// Prepare list of authorities
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		if (user.isAdmin())
			authorities.add(new GrantedAuthorityImpl(UserRole.ROLE_ADMIN));
		else
			authorities.add(new GrantedAuthorityImpl(UserRole.ROLE_USER));

		// Create a userDetails and return it
		return new CustomUserDetails(//
				username, password, enabled, accountNonExpired,//
				credentialsNonExpired, accountNonLocked, authorities, user);
	}
}
